XMLHttpRequest.prototype.sendAsBinary = function (file, param) {
	var formData = new FormData();
	formData.append('key', param.key);
	formData.append('token', param.token);
	formData.append('file', file);
	this.send(formData)
}

export default function changeAvatarHandle(event, callback) {
	var pic = event.target,
		pic_file = pic.files[0],
		pic_name = pic_file.name,
		startIndex = pic_name.lastIndexOf('.') + 1,
		pic_type = pic_name.substring(startIndex);

	getUploadParam(pic_type, function (data) {
		uploadFile(pic_file, data, uploadResult);
	});


    function uploadResult(result) {

        var img_src = 'http://cdn.ifenghuotai.cn/' + JSON.parse(result).key,
            url;
        pic.parentNode.style.backgroundImage = 'url(' + img_src + ')';
        callback(img_src)
        //avatarURL = img_src;

    }
}
function getUploadParam(type, callback) {
	var url = '/assets/request-token?ext_name=' + type;
	if (!type) { callback(false) }

	var xhr = new XMLHttpRequest();
	xhr.open('GET', url, true);
	xhr.send(null);
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4 && xhr.status == 200) {
			var get_data = JSON.parse(xhr.responseText);
			callback(get_data.data);

		}
	}


}
function uploadFile(file, param, callback) {
	var xhr = new XMLHttpRequest(),
		upload = xhr.upload;
	// if(progress){
	//     upload.addEventListener("progress", progress, false);
	// }
	xhr.open("POST", 'http://up.qiniu.com', true);
	xhr.sendAsBinary(file, param);
	xhr.onload = function () {
		if (xhr.responseText) {
			callback(xhr.responseText)
		}
	};
}


